'use strict';

exports.index = async ctx => {
  const { query } = ctx.request;
  let pageSize = 10;
  if (query.pageSize) pageSize = Number(query.pageSize);
  const where = {};
  const options = {
    limit: pageSize,
    offset: query.currentPage ? pageSize * (query.currentPage - 1) : 0,
    order: [
      [ 'order', 'DESC' ],
    ],
    raw: true,
    where,
  };
  const {
    count: total, rows: list,
  } = await ctx.model.Withdrawal.findAndCountAll(options);
  ctx.body = {
    list,
    pagination: {
      total,
      pageSize,
      current: parseInt(query.currentPage, 10) || 1,
    },
  };
};

exports.create = async ctx => {
  const loginService = ctx.app.weapp.LoginService.create(ctx.request, ctx.response);
  const checkedData = await loginService.check();
  const { openId, nickName } = checkedData.userInfo;
  const { userId } = await ctx.model.WechatAccount.findByPk(openId);
  const currentUser = await ctx.model.User.findByPk(userId);
  console.log('exports.create = async currentUser', currentUser);
  const phoneNumber = await ctx.model.Phone.findOne({ where: { userId: currentUser.id }, raw: true });
  const alipayAccount = await ctx.model.Alipay.findOne({ where: { userId: currentUser.id }, raw: true });
  console.log('phoneNumbephoneNumberphoneNumberphoneNumberr', phoneNumber);
  const currentBalance = Number(currentUser.balance);
  const data = {
    wechatAccountOpenId: openId,
    name: nickName,
    phone: phoneNumber.number,
    price: currentUser.balance,
    status: 'loading',
  };
  if (alipayAccount) {
    data.alipayName = alipayAccount.name;
    data.alipayAccount = alipayAccount.account;
  }
  const balanceRecord = {
    userId,
    balance: 0,
    price: currentUser.balance,
    add: false,
    remark: '提现消耗',
  };
  if (phoneNumber && currentUser.balance && currentBalance > 5000) {
    console.log('currentUser.balance && currentUser.balance > 5000');
    const withdrawal = await ctx.model.Withdrawal.create(data);
    await ctx.model.BalanceRecord.create(balanceRecord);
    await currentUser.update({ balance: 0 });
    ctx.status = 204;
    ctx.body = withdrawal;
  } else {
    ctx.status = 403;
  }

};
